package com.engine.jucailinkq.attendance.attendanceanalysis.cmd;

import com.engine.jucailinkq.attendance.enums.AccountingUnitEnum;
import com.engine.jucailinkq.attendance.enums.CheckBoxEnum;
import com.engine.jucailinkq.attendance.enums.ClassBelongToEnum;
import com.engine.jucailinkq.attendance.enums.ClassSegmentTypeEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.jucailinkq.common.util.*;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 获得出差数据
 */
@Slf4j
public class GetEvectionCmd extends AbstractCommonCommand<Map<String,Object>> {

    public GetEvectionCmd(Map<String,Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String,Object> resultMap = Maps.newHashMap();
        String userId = Util.null2String(params.get("userId"));
        String analysisDate = Util.null2String(params.get("analysisDate"));
        List<Map<String, Object>> scheduleResult =  (List<Map<String, Object>>)params.get("scheduleResult");
        //String sql = "select b.ccr,a.cclx,a.ccsd,b.ksrq,b.jsrq,b.kssj,b.jssj,b.ccsc,b.qtcc,b.btcc,b.cxcc from uf_jcl_kq_ccjl a left join uf_jcl_kq_ccjl_dt1 b on a.id = b.mainid where b.ccr=? and b.ksrq>=? and b.ksrq<=? and (b.cxcc=0 or b.cxcc is null)";
//        String sql = "select b.ccr,b.cclx,b.ksrq,b.jsrq,b.kssj,b.jssj,b.ccsc,b.qtcc,b.btcc,b.cxcc from uf_jcl_kq_ccjl a left join uf_jcl_kq_ccjl_dt1 b on a.id = b.mainid where b.ccr=? and b.ksrq<=? and b.jsrq>=? and (b.cxcc=0 or b.cxcc is null) and a.jlzt=1";
        String sql = "select b.ccr,b.cclx,b.ksrq,b.jsrq,b.kssj,b.jssj,b.ccsc,b.qtcc,b.btcc,b.cxcc from uf_jcl_kq_ccjl a left join (SELECT *\n" +
                "FROM (\n" +
                "    SELECT *,\n" +
                "           ROW_NUMBER() OVER (PARTITION BY ccr, ksrq, jsrq ORDER BY (SELECT NULL)) AS rn\n" +
                "    FROM uf_jcl_kq_ccjl_dt1\n" +
                ") t\n" +
                "WHERE t.rn = 1) b on a.id = b.mainid where b.ccr=? and b.ksrq<=? and b.jsrq>=? and (b.cxcc=0 or b.cxcc is null) and a.jlzt=1";
        List<Map<String,Object>> evectionList = DbTools.getSqlToList(sql,userId, DateUtil.AfterDay(analysisDate,1), DateUtil.beforeDay(analysisDate,1));
        Map<String,Map<String,Object>> evectionItems = Maps.newHashMap();

        String firstKssj = Utils.getkssjTime(scheduleResult.get(0),analysisDate);

        String lastjssj = Utils.getjssjTime(scheduleResult.get(scheduleResult.size()-1),analysisDate);

        Set<String> cclxSet = Sets.newHashSet();
        List<Map<String,Object>> haveEvectionList = evectionList.stream().filter(e->{
            String kssj = e.get("ksrq")+" "+e.get("kssj");
            String jssj = e.get("jsrq")+" "+e.get("jssj");
            if ((DateUtil.getTime(e.get("ksrq") + "").compareTo(DateUtil.getTime(analysisDate)) <= 0) && (DateUtil.getTime(e.get("jsrq") + "").compareTo(DateUtil.getTime(analysisDate)) >= 0) && "".equals(Util.null2String(e.get("kssj")))){
                cclxSet.add(e.get("cclx").toString());
                return true;
            }else if (!"".equals(Util.null2String(e.get("kssj"))) && DateUtil.getTime(kssj).compareTo(DateUtil.getTime(lastjssj)) <0 && DateUtil.getTime(jssj).compareTo(DateUtil.getTime(firstKssj)) >0){
                cclxSet.add(e.get("cclx").toString());
                return true;
            }else {
                return false;
            }
        }).collect(Collectors.toList());
        log.debug("haveEvectionList : [{}]",haveEvectionList);
        List<Map<String,Object>> resultList = Lists.newArrayList();
        List<Map<String,Object>> evectionSchedule = Lists.newArrayList();

        resultMap.put("evectionList",haveEvectionList);
        resultMap.put("evectionItems",evectionItems);
        resultMap.put("evectionSchedule",evectionSchedule);
        if (cclxSet.size() == 0){
            return resultMap;
        }
        sql = "select * from uf_jcl_kq_kqxm where id in ("+String.join(",",cclxSet)+")";
        List<Map<String,Object>> evectionItemList = DbTools.getSqlToList(sql);
        List<String> fatherItems = evectionItemList.stream().filter(e->Util.null2String(e.get("sffzcx")).equals(CheckBoxEnum.CHECKED.getKey())).map(e->e.get("id").toString()).collect(Collectors.toList());
        if (fatherItems.size() > 0){
            sql = "select id keyid,mc kqxm,a.* from uf_jcl_kq_kqxm a where  (xmzt is null or  xmzt <> '0') and a.sjxm in ("+String.join(",",fatherItems)+")";
            List<Map<String,Object>> sonItemList = DbTools.getSqlToList(sql);
            Map<String,List<Map<String,Object>>> sonGroupMap = sonItemList.stream().collect(Collectors.groupingBy(e->e.get("sjxm").toString()));
            for (Map<String,Object> evectionItem :evectionItemList){
                if (CheckBoxEnum.CHECKED.getKey().equals(evectionItem.get("sffzcx"))){
                    evectionItem.put("sonItems",sonGroupMap.get(evectionItem.get("id")));
                }
            }

        }

        Map<String,List<Map<String,Object>>> collect = evectionItemList.stream().collect(Collectors.groupingBy(e->e.get("id").toString()));


        for (Map<String,Object> evectionData : haveEvectionList){
            Map<String,Object> evectionItem = collect.get(evectionData.get("cclx")).get(0);
            //是否分组呈现
            String sffzcx = Util.null2String(evectionItem.get("sffzcx"));
            //全天出差
            if (CheckBoxEnum.CHECKED.getKey().equals(evectionData.get("qtcc"))){
                if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                    Map<String,Object> proportionMap = Utils.getClassSegmentTimeProportion(scheduleResult,analysisDate);
                    for (Map.Entry<String,Object> entry: proportionMap.entrySet()){
                        String bdlx = entry.getKey();
                        int betweenTimes = Integer.valueOf(entry.getValue().toString());
                        Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(evectionItem,bdlx);
                        if (item != null){
                            Map<String, Object> itemMap = Maps.newHashMap();
                            itemMap.put("itemduration",Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),betweenTimes, AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString())));
                            itemMap.put("item",item.get("keyid"));
                            resultList.add(itemMap);
                        }
                    }
                }else {
                    Map<String,Object> map = Maps.newHashMap();
                    map.put("item",evectionData.get("cclx"));
                    map.put("itemduration",scheduleResult.get(0).get("edsc"));
                    resultList.add(map);
                }

                resultMap.put("alldayEvection",resultList);
            }

            evectionItems.put(evectionData.get("cclx").toString(),evectionItem);
        }

        Map<String,List<Map<String,Object>>> evectionGroupMap = haveEvectionList.stream().filter(e->!"".equals(Util.null2String(e.get("kssj"))) && !"".equals(Util.null2String(e.get("jssj"))))
                .collect(Collectors.groupingBy(e->Util.null2String(e.get("ksrq"))+Util.null2String(e.get("kssj"))+"&"+Util.null2String(e.get("jsrq"))+Util.null2String(e.get("jssj"))));
        List<Map<String,Object>> filterEvectionList = Lists.newArrayList();
        evectionGroupMap.entrySet().forEach(e->{
            if (e.getValue().size()>1){
                Map<String,Object> beforeEvectionMap = e.getValue().get(0);
                Map<String,Object> beforeEvectionItem = collect.get(beforeEvectionMap.get("jqlx")).get(0);
                String beforeJcbyxsyqjb = Util.null2String(beforeEvectionItem.get("jcbyxsyqjb"));
                String beforeyxsydjb = Util.null2String(beforeEvectionItem.get("yxsydjb"));
                Map<String,Object> afterEvectionMap = e.getValue().get(1);
                Map<String,Object> afterEvectionItem = collect.get(afterEvectionMap.get("jqlx")).get(0);
                String afterJcbyxsyqjb = Util.null2String(afterEvectionItem.get("jcbyxsyqjb"));
                String afteryxsydjb = Util.null2String(afterEvectionItem.get("yxsydjb"));
                if (CheckBoxEnum.CHECKED.getKey().equals(beforeJcbyxsyqjb)){
                    if (beforeyxsydjb.equals(afterEvectionMap.get("jqlx"))){
                        filterEvectionList.add(beforeEvectionMap);
                    }

                }else if (CheckBoxEnum.CHECKED.getKey().equals(afterJcbyxsyqjb)){
                    if (afteryxsydjb.equals(beforeEvectionMap.get("jqlx"))){
                        filterEvectionList.add(afterEvectionMap);
                    }
                }else {
                    filterEvectionList.add(beforeEvectionMap);
                }

            }else if (e.getValue().size() == 1){
                filterEvectionList.addAll(e.getValue());
            }
        });


        for (Map<String,Object> evectionData : filterEvectionList){
            Map<String,Object> evectionItem = collect.get(evectionData.get("cclx")).get(0);
            if (!"".equals(Util.null2String(evectionData.get("kssj"))) && !"".equals(Util.null2String(evectionData.get("jssj")))){
                Map<String,Object> evectioneMap = new HashMap(){{
                    put("bcxx", scheduleResult.get(0).get("bcxx"));
                    put("bcsdxx", scheduleResult.get(0).get("bcsdxx"));
                    put("edsc", scheduleResult.get(0).get("edsc"));
                    put("bdlx", ClassSegmentTypeEnum.EVECTION.getKey());
                    put("dtkssj",evectionData.get("ksrq")+" "+evectionData.get("kssj"));
                    put("dtjssj",evectionData.get("jsrq")+" "+evectionData.get("jssj"));
                    put("ksdk",evectionItem.get("lgsbxydk"));
                    put("jsdk",evectionItem.get("fgsbxydk"));
                    put("tqdkfzs", ExtensionClassHolder.getGlobalSetMap().get("defaultClockRange") == null?"60":ExtensionClassHolder.getGlobalSetMap().get("defaultClockRange"));
                    put("thdkfzs", ExtensionClassHolder.getGlobalSetMap().get("defaultClockRange")== null?"60":ExtensionClassHolder.getGlobalSetMap().get("defaultClockRange"));
                    put("tqlghlfzs",evectionItem.get("tqlghlfzs"));
                    put("thfghlfzs",evectionItem.get("thfghlfzs"));
                    put("zysd",evectionItem.get("zysd"));
                }};
                evectionSchedule.add(evectioneMap);
            }
        }


        return resultMap;
    }
}
